<template>
    <div>
      <h1>在线聊天</h1>
      <Chat :messages="messages" @send="sendMessage" />
    </div>
  </template>

<script>
import Chat from './index.vue'

export default {
  name: 'App',
  components: {
    Chat
  },
  data () {
    return {
      messages: []
    }
  },
  mounted () {
    this.connect()
  },
  methods: {
    connect () {
      const socket = new WebSocket('ws://localhost:3029')

      socket.addEventListener('message', (event) => {
        const message = JSON.parse(event.data)
        this.messages.push(message)
      })
    },
    sendMessage (message) {
      const socket = new WebSocket('ws://localhost:3029')
      socket.addEventListener('open', () => {
        socket.send(JSON.stringify(message))
      })
    }
  }
}
</script>
